package com.rcw.popup;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.rcw.filterpopup.R;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by ruancw on 2018/5/31.
 * 自定义类似流式布局的筛选popupWindow
 */

public class FilterPopupWindow extends PopupWindow{

    private FilterPopupWindow(Context context, View view){
        //这里可以修改popupWindow的宽高
        super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(view);
        //设置有焦点
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable());
        //设置点击外部可消失
        setOutsideTouchable(true);
    }

    /**
     * 重写showAsDropDown方法，解决高版本不在控件下方显示的问题
     * @param anchor popupWindow要显示在的控件
     */
    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }

    /**
     * 自定义的内部类，用于设置参数
     *
     */
    public static class Builder {
        private Context context;//上下文对象
        private LinearLayout llContent;//popupWindow的内容显示

        private List<String> mValuesList;//存储取值的集合
        private List<String> mParentList;//一级菜单数据集合
        private List<String> mChildList;//二级菜单数据集合
        private FilterAdapter mParentAdapter, mChildAdapter;
        private RecyclerView mRvParent, mRvChild;

        //背景颜色
        private int colorBg = Color.parseColor("#FFFFFF");

        private FilterPopupWindow mFlowPopupWindow;

        public Builder(Context context) {
            this.context = context;
        }

        /**
         * 设置一级菜单数据，二级菜单数据根据一级条目获取
         * @param mParentList 一级菜单数据
         */
        public void setValue(List<String> mParentList) {
            this.mParentList = mParentList;
        }

        /**
         * 设置内容区域的背景色
         * @param color 颜色
         */
        public void setBgColor(int color){
            colorBg = context.getResources().getColor(color);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void build(){
            //初始化popupWindow的布局文件
            initPopup();
        }


        /**
         * 初始化PopupWindow的布局
         */
        private void initPopup(){
            //初始化popupWindow的布局文件
            @SuppressLint("InflateParams")
            View view = LayoutInflater.from(context).inflate(R.layout.popup_layout,null);
            //主要用于设置数据显示区域的背景色
            LinearLayout ll= (LinearLayout) view.findViewById(R.id.ll);

            //设置数据展示区域的背景色
            ll.setBackgroundColor(colorBg);
            llContent = new LinearLayout(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            view.setLayoutParams(params);
            llContent.addView(view);
            //设置背景色，不设置的话在有些机型会不显示popupWindow
            llContent.setBackgroundColor(Color.parseColor("#66F6F6F6"));
            //llContent.setBackgroundColor(Color.argb(60, 0, 0, 0));
            //展示一级菜单的view
            mRvParent = (RecyclerView) view.findViewById(R.id.rv_parent);
            //展示二级菜单的view
            mRvChild = (RecyclerView) view.findViewById(R.id.rv_child);
            //存储取值列表的集合
            mValuesList = new ArrayList<>();
            //默认添加一级菜单对应的二级菜单的第一个值列表
            //mValuesList.addAll(mChildList.get(0));

            mRvParent.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            mRvParent.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
            mRvChild.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            mRvChild.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
            //创建一级和二级菜单的adapter
            mParentAdapter = new FilterAdapter(context, R.layout.popup_item, mParentList);
            mChildAdapter = new FilterAdapter(context, R.layout.popup_child_item, mValuesList);
            //设置一级菜单的第一个默认选中状态
            mParentAdapter.recordSelectPosition(0);
            mRvParent.setAdapter(mParentAdapter);
            mRvChild.setAdapter(mChildAdapter);

            //父条目点击事件
            mParentAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    if (position == 0) {
                        //position=0为筛选全部，点击popupWindow消失并设置取值为父条目的第一个值
                        hidePopup(mParentList.get(position));
                        return;
                    }
                    //记录父条目点击的position
                    mParentAdapter.recordSelectPosition(position);
                    mParentAdapter.notifyDataSetChanged();
                    mValuesList.clear();
                    //模拟加载子类数据
                    initChildData(mParentList.get(position));

                    //设置子条目默认选中第一个
                    //mRvChild.scrollToPosition(0);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }

            });
            //子条目点击事件
            mChildAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    //记录子条目点击的position
                    mChildAdapter.recordSelectPosition(position);
                    mChildAdapter.notifyDataSetChanged();
                    //隐藏popupWindow
                    hidePopup(mValuesList.get(position));
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }

            });

        }


        private void initChildData(String grade) {
            String gradeCode=grade.substring(0,1);
            mChildList = new ArrayList<>();
            for (int j = 0; j < 15; j++) {
                if (j < 9) {
                    mChildList.add(gradeCode + "-0" + (j + 1) + "班");
                } else mChildList.add(gradeCode + "-" + (j + 1) + "班");
            }
            //将子条目添加到取值列表
            mValuesList.addAll(mChildList);
            mChildAdapter.notifyDataSetChanged();
            mChildAdapter.recordSelectPosition(-1);
        }

        /**
         * 隐藏popupWindow
         * @param value 获取的结果值
         */
        private void hidePopup(String value) {
            if (mFlowPopupWindow != null&&mFlowPopupWindow.isShowing()){
                filterPopupMonitor.setFilterResult(value);
                mFlowPopupWindow.dismiss();
            }
        }


        /**
         * 创建popupWindow
         * @return FlowPopupWindow实例
         */
        public FilterPopupWindow createPopup(){
            mFlowPopupWindow = new FilterPopupWindow(context,llContent);
            return mFlowPopupWindow;
        }

    }

    private static FilterPopupMonitor filterPopupMonitor;

    /**
     * 监听数据的接口
     */
    public interface FilterPopupMonitor {
        //设置回调的方法
        void setFilterResult(String filterResult);
    }

    /**
     * 接口绑定
     * @param filterPopupMonitor 接口
     */
    public void setFilterPopMonitor(FilterPopupMonitor filterPopupMonitor) {
        FilterPopupWindow.filterPopupMonitor = filterPopupMonitor;
    }

}
